/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.dispatch.controller;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.Constants;
import offset.nodes.server.config.NodesConfig;
import offset.nodes.server.controller.AuthenticatingAction;
import offset.nodes.server.controller.EditorAttribute;
import offset.nodes.server.controller.contentType.ContentTypeDispatcher;
import offset.nodes.server.model.RepositoryModel;
import offset.nodes.server.model.RepositoryUtils;
import offset.nodes.server.version.model.FrozenNode;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Walter Lütgenau
 */
public class DispatchAction extends AuthenticatingAction {

    public static final String PARAMETER_PATH = "path";

    /** Creates a new instance of DispatchAction */
    public DispatchAction() {
    }

    public ActionForward process(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        DispatchForm dispatchForm = (DispatchForm) form;

        String contentType = Constants.CONTENT_TYPE_DEFAULT;
        Node node = null;
        String path = null;

        try {
            RepositoryUtils.setRepositoryURL(request);
            RepositoryModel model = new RepositoryModel(getRepositorySession(request));

            path = urlDecode(request.getPathInfo());
            if (dispatchForm.getReference() != null) { // must be a UUID
                // must be a UUID
                node = model.getNodeByUuid(dispatchForm.getReference());
                if (node != null)
                    path = node.getPath();
                else
                    return null;
            } else
                node = model.getNode(path);

            if (node != null)
                if (node.isNodeType(Constants.NT_FROZEN_NODE)) // simulate an ordinary node
                    node = new FrozenNode(node);
                else
                    path = node.getPath();
            contentType = ContentTypeDispatcher.getInstance().getContentType(node, request);
        } catch (Exception ex) {
            Logger.getLogger(DispatchAction.class.getName()).log(Level.SEVERE, null, ex);
            return mapping.findForward("error");
        }

        DispatchAttribute dispatch = new DispatchAttribute();
        dispatch.setNode(node);
        dispatch.setPath(path);
        dispatch.setContentType(contentType);
        request.setAttribute(DispatchAttribute.ATT_DISPATCH, dispatch);
        if (dispatchForm.isEdit())
            request.setAttribute(EditorAttribute.ATT_EDITOR, new EditorAttribute());

        ActionForward forward = NodesConfig.getInstance().getNavigationConfig().getActionForward(this.getClass().getName(), contentType);

        return addParameter(forward, PARAMETER_PATH, path);
    }

    /**
     * Decode a string encoded by the output link tag, optionally. That is, substitute
     * the unwanted '+' signs by spaces.
     *
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     */
    protected String urlDecode(String url) throws UnsupportedEncodingException {
        if (url == null)
            return null;
        return url.replaceAll("\\+", " ");
    }

}
